var koa = require('koa');
var router = require("koa-router");
var bodyParser = require("koa-body-parser");
var app = koa();
var green_orgin_list = require("../origin").origin;
var green_orgin_map = {};
green_orgin_list.forEach(function (origin) {
  green_orgin_map[origin] = true;
});
/* 查找配置文件并进行相关的初始化 */
;(function(){
  console.log("初始化配置文件")
  var fs = require("./_include/fs");
  var fs_list = [
    "server/_include/.errorSet/errorSet.json",
    "core/db/.db/data.cache.json",
    "core/db/.db/index.cache.json"
  ];
  fs_list.forEach(function (file_path) {
    try{
      fs.fs.readFileSync(file_path);
    }catch(e){
      // file_path = __dirname+file_path;
      var folder_path = file_path.split("/");
      folder_path.pop();
      folder_path = folder_path.join("/");
      fs.mkdir(folder_path);
      fs.file(file_path,"{}");
      console.log(file_path,folder_path,file_path);
    }
  });
  console.log("初始化配置文件完毕");
}());

//设置运行的请求域
app.use(function *(next) {
  // console.log(this.req.headers)
  var origin = this.req.headers.origin||"";
  console.log("origin:",origin);
  var origin_result = "http://www.datnor.com";
  if (origin.indexOf("http://localhost:")===0||origin.indexOf("http://192.168.")===0) {
    //开发模式
    origin_result = origin;
  }else {
    //从白名单中进行匹配
    var pathname = origin.replace("http://","").replace("https://","");
    if (green_orgin_map[pathname]) {
      origin_result = origin;
    }else{
      var pathname_info = pathname.split(".");
      if (pathname_info[pathname_info.length-1].indexOf("com")===0&&pathname_info[pathname_info.length-2]==="dotnar") {
        origin_result = origin;
      }
    }
  }
  this.set("Access-Control-Allow-Credentials",true);
  this.set("Access-Control-Allow-Origin", origin_result);
  this.set("Access-Control-Allow-Methods","POST,GET,PUT,DELETE,OPTIONS");
  this.set("Access-Control-Allow-Headers","X-PINGOTHER, Set-Cookie, X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5, Content-Type, Date, X-Api-Version")
  //设定P3P规范
  this.set("P3P","CP=CAO PSA OUR");
  // console.log(this.res)
	yield next;
});

//对于IE浏览器，跨域共享Cookie默认是非安全行为。故使用query里携带Cookie信息来解决
app.use(function *(next) {
  //如果Cookie为空，尝试从query中获取
  if (!this.req.headers["cookie"]) {
    this.req.headers["cookie"] = this.request.query.cors_cookie;
  }
  // console.log("cookies:",this.req.headers["cookie"],this.request.query,this.request.query.cors_cookie);
  yield next;
});

// x-response-time 计算响应时间

app.use(function *(next){
  var start = new Date;
  yield next;
  var ms = new Date - start;
  this.set('X-Response-Time', ms + 'ms');
});

// logger 打印请求日志

app.use(function *(next){
  var start = new Date;
  yield next;
  var ms = new Date - start;
  console.log('%s %s - %s', this.method, this.url, ms);
});

//参数解析器

app.use(bodyParser());

// router 路由器

app.use(router(app));
require("./routerMap")(app);

app.listen(3000);